// 病友圈详情页面组件


import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
// import './PatientCircleDetail.scss';
import { getHttp } from '../../request/api';
import './Index.scss';
import { NavBar, Loading } from 'react-vant';
import { useNavigate } from 'react-router-dom';
import CommentComponent from '../../components/Comment/Index';
import { Like, Comment as CommentIcon, Share } from '@react-vant/icons';

interface PatientCircleDetailData {
  sickCircleId: number;
  authorUserId: number;
  departmentId: number;
  adoptFlag: number;
  title: string;
  department: string;
  disease: string;
  detail: string;
  treatmentHospital: string;
  treatmentStartTime: string;
  treatmentEndTime: string;
  treatmentProcess: string;
  picture: string;
  collectionFlag: number;
  collectionNum: number;
  commentNum: number;
  adoptNickName?: string;
  adoptHeadPic?: string;
  adoptComment?: string;
  adoptTime?: number;
}

// 定义时间戳转换函数
const formatTimestamp = (timestamp: number | string): string => {
  const date = new Date(Number(timestamp));
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');

  return `${year}-${month}-${day}`;
};

const PatientCircleDetail: React.FC = () => {
  const navigate = useNavigate();
  const { sickCircleId } = useParams<{ sickCircleId: string }>();
  const [loading, setLoading] = useState<boolean>(true);
  const [data, setData] = useState<PatientCircleDetailData | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [isFollowed, setIsFollowed] = useState<boolean>(false); // 假设初始状态为未关注
  const [commentList, setCommentList] = useState<any[]>([]);
  const [commentText, setCommentText] = useState('');
  const [likes, setLikes] = useState(0);

  const fetchData = async () => {
    try {
      const response = await getHttp(`/health/user/sickCircle/v1/findSickCircleInfo`, { sickCircleId });
      
      console.log(response, 'response');
      setData(response.data.result);
      if (response.data.result?.collectionNum !== undefined) {
        setLikes(response.data.result.collectionNum);
      }
      setLoading(false);
    } catch (err) {
      console.error('Failed to fetch data:', err);
      setError('Failed to fetch data');
      setLoading(false);
    }
  };

  const fetc = async () => {
    console.log(111, 'sickCircleId');
    try {
      const params = {
        sickCircleId,
        page: 1,
        count: 4
      }
      const response = await getHttp(`/health/user/sickCircle/v1/findSickCircleCommentList`, params);
      console.log(response, 'response');
      setCommentList(response.data.result);
      setLoading(false);
    } catch (err) {
      console.error('Failed to fetch data:', err);
      setError('Failed to fetch data');
      setLoading(false);
    }
  };
  useEffect(() => {
    fetchData();
    fetc()
  }, [sickCircleId]);

  const onGivealike = async (e: React.MouseEvent<HTMLImageElement>) => {
    if (!data) return;

    try {
      // Toggle like status
      const newLikeCount = isFollowed ? likes - 1 : likes + 1;
      setLikes(newLikeCount);
      setIsFollowed(!isFollowed);

      // Update data object
      setData({
        ...data,
        collectionNum: newLikeCount,
        collectionFlag: isFollowed ? 2 : 1
      });
    } catch (err) {
      console.error('Failed to update like:', err);
    }
  };

  const handleCommentSuccess = () => {
    // 评论成功后刷新数据
    fetchData();
  };

  if (loading) {
    return (
      <div className="loading-container">
        <Loading type="spinner" />
        <span>加载中...</span>
      </div>
    );
  }

  if (error) {
    return <div className="error-message">{error}</div>;
  }

  if (!data) {
    return <div className="no-data">暂无数据</div>;
  }

  // 格式化治疗时间
  const treatmentStartTime = formatTimestamp(data.treatmentStartTime);
  const treatmentEndTime = formatTimestamp(data.treatmentEndTime);
  const treatmentTime = `${treatmentStartTime} - ${treatmentEndTime}`;

  return (
    <div className="patient-circle-detail">
      <NavBar
        title="病友圈详情"
        leftText="返回"
        onClickLeft={() => navigate('/moments')}
        fixed
      />

      <div className="patient-circle-detail-container">
        <div className="patient-circle-detail-scroll-container">
          <p className="user-name"></p>
          {/* 病症信息块 */}
          <div className="info-item">
            <span className="title-bracket">[病症]</span>
            <p className="info-content">{data.disease}</p>
          </div>
          {/* 科室信息块 */}
          <div className="info-item">
            <span className="title-bracket">[科室]</span>
            <p className="info-content">{data.department}</p>
          </div>
          {/* 病症详情 */}
          <div className="section">
            <span className="title-bracket">[病症详情]</span>
            <p className="section-content">{data.detail}</p>
          </div>
          {/* 治疗经历 */}
          <div className="section">
            <span className="title-bracket">[治疗经历]</span>
            <div className="treatment">
              <p className="hospital">{data.treatmentHospital}</p>
              <span className="time">{treatmentTime}</span>
            </div>
            <p className="treatment-content">{data.treatmentProcess}</p>
          </div>
          {/* 相关图片，无数据时显示白色盒子内容"暂无" */}
          <div className="section">
            <span className="title-bracket">[相关图片]</span>
            {data.picture ? (
              <img src={data.picture} alt="诊疗记录" className="record-image" />
            ) : (
              <div className="no-data-box">暂无</div>
            )}
          </div>
          {/* 统计信息 */}
          <div className="stats">
            <span className="star">
              <img
                className='star-img'
                onClick={onGivealike}
                src={isFollowed ? '/images/image/xxhdpi/evaluation_star_s.png' : '/images/image/xxhdpi/evaluation_star_n.png'}
                alt=""
              />
              {data.collectionNum}
            </span>
            <span className="comment">
              <img className='star-img' src='/images/image/xxhdpi/interview_news.png' alt="" />
              {data.commentNum}
            </span>
          </div>
          {/* 评论组件 */}
          <div className="comment-section">
            <div className="comment-list">
              <span className="section-title">全部评论{commentList.length}</span>
              {commentList.length === 0 ? (
                <div className="no-comments">暂无评论，快来抢沙发~</div>
              ) : (
                <div className="comment-list-container">
                  {commentList.map((item: any) => (
                    <div className="comment-item" key={item.commentId}>
                      <div className="comment-header">
                        <img
                          src={'https://img1.baidu.com/it/u=1052397826,1513523633&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500'}
                          alt="用户头像"
                          style={{ width: '40px', height: '40px', borderRight: '20px' }}
                          className="avatar"
                        />
                        <div className="name-wrapper">
                          <span className="nickname">{item.nickName ? item.nickName : '匿名用户'}</span>
                          {item.whetherDoctor === 1 && (
                            <span className="doctor-tag">医生</span>
                          )}
                        </div>
                        <div className="user-info">

                          <span className="comment-time">
                            {item.content}
                          </span>
                        </div>
                      </div>
                      <p className="comment-content"> {formatTimestamp(item.commentTime)} </p>
                      <div className="comment-actions">
                        <div className="vote-wrapper">
                          {/* <button onClick={() => {
                          setCommentText('supportNum')
                          onGivealike(item)
                        }
                        } className={`vote-btn ${item.opinion === 1 ? 'active' : ''}`}>
                          <span></span> {item.supportNum}
                        </button>
                        <div className="divider"></div>
                        <button onClick={() => {
                          setCommentText('opposeNum')
                          onGivealike(item)
                        }
                        } className={`vote-btn ${item.opinion === 2 ? 'active' : ''}`}>
                          <span></span> {item.opposeNum}
                        </button> */}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
            <h3 className="section-title">发表建议</h3>
            <CommentComponent
              sickCircleId={data.sickCircleId}
              onCommentSuccess={handleCommentSuccess}
              onCommentSucce={fetc}
            />
          </div>
          {/* 被采纳的建议，无数据时显示白色盒子内容"暂无" */}
          <div className="suggestion">
            <span className="section-title">被采纳的建议</span>
            {data.adoptComment ? (
              <div className="suggestion-item">
                {data.adoptHeadPic && (
                  <img src={'https://img0.baidu.com/it/u=2317612037,2363737113&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500'} alt="用户头像" className="avatar" />
                )}
                <div className="suggestion-content">
                  <p className="user">{data.adoptNickName || '匿名用户'}</p>
                  {data.adoptTime && (
                    <span className="time">
                      {formatTimestamp(data.adoptTime)}
                    </span>
                  )}
                  <p className="text">{data.adoptComment}</p>
                </div>
              </div>
            ) : (
              <div className="no-data-box">暂无</div>
            )}
          </div>
        </div>
      </div>
      <div className="patient-circle-detail-footer">
      </div>
    </div>
  );
};

export default PatientCircleDetail;